import java.io.IOException;

public class QueryWorker implements Runnable
{
	Faculty faculty;
	String college;

	public QueryWorker(Faculty fac, String college)
	{
		this.faculty = fac;
		this.college = college;
	}
	
	@Override
	public void run()
	{
        query(faculty);
    }
    
	protected void done()
	{
		System.out.println("Done");
	}
	
	public String formatName(String name)
	{
		String newName = name.toLowerCase();
		newName = newName.replace(' ', '+');
		return newName;
	}
	
	public void query(Faculty fac)
	{
		String lecturerName = "";
		System.out.println(fac.getName() + " - " + college);
		String collegeName = formatName(college);
		String subject = fac.getType();
		System.out.println("total staff: " + fac.getTotalStaffMembers());
		GoogleParser googleparser;
		while(fac.hasNext())
		//for(int i = 0; i < 5; i++)
		{
			Person person = new Person();
			person = fac.next();
			lecturerName = person.formatName();
			String query = "http://scholar.google.com/scholar?as_q="+collegeName+
							"&num=100&as_sauthors="+lecturerName+"&as_subj="+subject;
			System.out.println("Query:" + query);
			HttpClient http = new HttpClient();
			try
			{

				StringBuffer searchResult = new StringBuffer(http.GETRequest(query));

				googleparser = new GoogleParser(searchResult);
				System.out.println("(parsing)");
				System.out.println("total Papers: " +googleparser.getTotalPapers());
				System.out.println("total citations: " +googleparser.getTotalCitations());
				System.out.println("page high: "+ googleparser.getPageHighest());
				
				int startNum = 100;
				int currentHighest = googleparser.getPageHighest();
				int totalCites = googleparser.getTotalCitations();
				System.out.println("papers: "+googleparser.getTotalPapers()+" cites: "+ totalCites);
				while(currentHighest < googleparser.getTotalPapers())
				{
					System.out.println("re-querying");
					query = "http://scholar.google.com/scholar?as_q="+collegeName+
					"&num=100&as_sauthors="+lecturerName+"&as_subj="+subject+"&start="+startNum+"&sa=N";
					
					searchResult = new StringBuffer(http.GETRequest(query));
					googleparser = new GoogleParser(searchResult);
					
					totalCites += googleparser.getTotalCitations();
					System.out.println("page high: "+ googleparser.getPageHighest());
					startNum += 100;
				}
				
				System.out.println("papers: "+googleparser.getTotalPapers()+" cites: "+ totalCites);
				
				fac.setTotalFacultyPapers(fac.getTotalFacultyPapers() + googleparser.getTotalPapers());
				fac.setTotalFacultyCitations(fac.getTotalFacultyCitations() + totalCites);
			}
			catch(IOException e)
			{
				System.err.println(e);
			}
		}
	}
}
